#!/usr/bin/env python

import os, sys, urllib
from xml.dom.ext.reader import Sax2
reader = Sax2.reader()


templateFilename = "source/template.xml"
javascriptFilename = "source/code.js"
targetFilename = "bom.xml"
oldLocationsFilename = "source/oldLocations.csv"

locationsMarker = "<<<locations>>>"
javascriptMarker = "<<<javascript>>>"

def main():
        # Read in the template
        template = file(templateFilename).read()

        # Insert the javascript into the template
        destination = template.replace(javascriptMarker, file(javascriptFilename).read())

        # Build the locations
        locationsText = buildLocations()

        # Insert the locations into the template
        destination = destination.replace(locationsMarker, locationsText)

        # Write out the completed XML file
        file(targetFilename, "w").write(destination)

def buildLocations():
        """
                Use the static list of locations for the 'old' state(s), and generate the locations for the 'new' states from their XML
        """
        xmlInfo = dict() # key is state abbreviation, value is tuple: (metro detailed forecasts XML URL, precis forecasts XML URL)
        xmlInfo["VIC"] = ("ftp://ftp.bom.gov.au/anon/gen/fwo/IDV10450.xml", "ftp://ftp.bom.gov.au/anon/gen/fwo/IDV10753.xml")
        
        #### First read in the 'old' locations, except for those we'll populate from the XML
        # each entry is (state, internal name,1 if metro, long, lat, display name
        locations = [row.split("|") for row in file(oldLocationsFilename) if row[0] not in xmlInfo]


        # Now build the new locations for each state
        for state, (detailedXMLURL, precisXMLURL) in xmlInfo.iteritems():
                dXML = reader.fromStream(urllib.urlopen(detailedXMLURL).read())
                dNodes = xpath.Evaluate('', dXML.documentElement)


        return ""


if __name__ == '__main__':
        main()
